package com.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

//@Component
//@Aspect //标注后说明是切面类
public class MyAspect {
    //public:UserService方法的修饰符
    //* : 返回值
    //com.service.UserService.save():唯一定位
    //execution(public * com.service.UserService.save())

    //@Before("execution(public * com.service.UserService.save())")
    //控制到GoodsService的delete
    //@Before("execution(public * com.service.GoodsService.delete(..))")
    //控制到service文件夹下面所有类所有方法
    //@Before("execution(public * com.service.*.*(..))")
/*    @Before("execution(* com.service.*.*(..))")
    public void before(){
        System.out.println("my aspect before....");
    }*/

    //控制到service文件夹下面所有类所有方法
/*    @After("execution(* com.service.*.*(..))")
    public void after(){
        System.out.println("my aspect after....");
    }*/

    //@Around=before+after
    @Around("execution(* com.service.*.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("around before");
        Object ret = joinPoint.proceed();//执行方法
        System.out.println("around ret->"+ret);
        System.out.println("around after");
        return ret;
    }

    //返回执行return之后再执行 可以获取到返回值
    @AfterReturning(value = "execution(* com.service.*.*(..))",returning = "ret")
    public void afterReturn(Object ret){
        System.out.println("方法return之后....ret->"+ret);
    }

    //获取到异常信息 下一步可以将异常记录到日志 或者发送警告等等
    //自定义异常:如果抛出来的异常是我们指定的异常 那就可以实现定制化异常报警
    @AfterThrowing(value = "execution(* com.service.UserService.save())",throwing = "e")
    public void afterThrowing(Throwable e){
        if(e instanceof NullPointerException){
            System.out.println("获取到方法的异常:e->"+e.getMessage());
        }else{
            System.out.println("未知异常....");
        }
    }

}
